<template>
  <a-tabs type="card" default-active-key="1" size="small">
    <a-tab-pane key="1" tab="样式">
      <a-form :model="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 18 }" style="margin-left: 5px">
        <a-form-item label="标题">
          <a-input :value="curLabel" @change="handleLabel" />
        </a-form-item>
        <a-form-item label="字号">
          <a-input-number :value="curFontSize" @change="handleFontsize" />
        </a-form-item>
        <a-form-item label="文字">
          <a-popover
              placement="leftTop"
              trigger="click"
              title="修改文字颜色"
              v-model:visible="textColorVisible"
          >
            <template #content>
              <a-row style="margin-bottom: 10px">
                <Sketch :modelValue="colors" @update:modelValue="updateTextFill" :presetColors="presetColors" />
              </a-row>
              <a-row>
                <a-col :span="17">
                  <a-button @click="textColorVisible = false">取消</a-button>
                </a-col>
                <a-col :span="7">
                  <a-button type="primary" @click="handleTextFill">确定</a-button>
                </a-col>
              </a-row>
            </template>
            <div class="color-container" @click="textColorVisible = true">
              <div class="edit-color" :style="{ backgroundColor: curNode.attrs?.text?.fill || '' }"></div>
            </div>
          </a-popover>
        </a-form-item>
        <a-form-item label="填充">
          <a-popover
              :visible="fillColorVisible"
              placement="leftTop"
              trigger="click"
              title="修改填充色"
              @visibleChange="visible => (fillColorVisible = visible)"
          >
            <template #content>
              <a-row style="margin-bottom: 10px">
                <Sketch :modelValue="colors" @update:modelValue="updateBodyFill" :presetColors="presetColors" />
              </a-row>
              <a-row>
                <a-col :span="17">
                  <a-button @click="fillColorVisible = false">取消</a-button>
                </a-col>
                <a-col :span="7">
                  <a-button type="primary" @click="handleBodyFill">确定</a-button>
                </a-col>
              </a-row>
            </template>
            <div class="color-container" @click="fillColorVisible = true">
              <div class="edit-color" :style="{ backgroundColor: curNode.attrs?.body?.fill || '' }"></div>
            </div>
          </a-popover>
        </a-form-item>
        <a-form-item label="边框">
          <a-popover
              :visible="strokeColorVisible"
              placement="leftTop"
              trigger="click"
              title="修改边框色"
              @visibleChange="visible => (strokeColorVisible = visible)"
          >
            <template #content>
              <a-row style="margin-bottom: 10px">
                <Sketch :modelValue="colors" @update:modelValue="updateBodyStroke" :presetColors="presetColors" />
              </a-row>
              <a-row>
                <a-col :span="17">
                  <a-button @click="strokeColorVisible = false">取消</a-button>
                </a-col>
                <a-col :span="7">
                  <a-button type="primary" @click="handleBodyStroke">确定</a-button>
                </a-col>
              </a-row>
            </template>
            <div class="color-container" @click="strokeColorVisible = true">
              <div class="edit-color" :style="{ backgroundColor: curNode.attrs?.body?.stroke || '' }"></div>
            </div>
          </a-popover>
        </a-form-item>
      </a-form>
    </a-tab-pane>
    <a-tab-pane key="2" tab="属性">
      <a-form
          :model="formData"
          :label-col="{ span: 5 }"
          :wrapper-col="{ span: 18 }"
          style="margin-left: 5px"
      >
        <a-form-item label="工厂">
          <a-space>
            <span>{{ formData.factoryName }}</span>
            <a-input v-model:value="formData.factorySearch" placeholder="输入查询" />
          </a-space>
        </a-form-item>
        <a-form-item label="产线">
          <a-space>
            <span>{{ formData.lineName }}</span>
            <a-input v-model:value="formData.lineSearch" placeholder="输入查询" />
          </a-space>
        </a-form-item>
        <a-form-item label="产品">
          <a-space>
            <span>{{ formData.productName }}</span>
            <a-input v-model:value="formData.productSearch" placeholder="输入查询" />
          </a-space>
        </a-form-item>
        <a-form-item label="是最新版本">
          <a-select v-model:value="formData.isLatest" :options="yesNoOptions" placeholder="请选择" />
        </a-form-item>
        <a-form-item label="类型">
          <a-select v-model:value="formData.type" :options="typeOptions" placeholder="请选择类型" />
        </a-form-item>
        <a-form-item label="代码">
          <a-input v-model:value="formData.code" />
        </a-form-item>
        <a-form-item label="名称">
          <a-input v-model:value="formData.name" />
        </a-form-item>
        <a-form-item label="JPH">
          <a-input v-model:value="formData.jph" />
        </a-form-item>
        <a-form-item label="版本">
          <a-input v-model:value="formData.version" />
        </a-form-item>
        <a-form-item :wrapper-col="{ offset: 5, span: 18 }">
          <a-button type="primary" @click="handleSaveDeviceAttribute">保存</a-button>
        </a-form-item>
      </a-form>
    </a-tab-pane>
    <a-tab-pane key="3" tab="设备">
      <div style="margin-left: 5px; margin-right: 5px">
        <a-table
            :columns="deviceColumns"
            :data-source="deviceList"
            :pagination="false"
            row-key="code"
            size="small"
            bordered
        />
        <a-form
            :model="deviceForm"
            :label-col="{ span: 5 }"
            :wrapper-col="{ span: 18 }"
            style="margin-top: 20px"
        >
          <a-form-item label="设备编码">
            <a-input v-model:value="deviceForm.code" />
          </a-form-item>
          <a-form-item label="设备名称">
            <a-input v-model:value="deviceForm.name" />
          </a-form-item>
          <a-form-item label="设备供应商">
            <a-input v-model:value="deviceForm.vendor" />
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 5, span: 18 }">
            <a-button type="primary" @click="handleDeviceSave">添加设备</a-button>
          </a-form-item>
        </a-form>
      </div>
    </a-tab-pane>
  </a-tabs>
</template>

<script setup>
import { ref, watch, reactive, watchEffect, computed } from 'vue';
import { Node } from '@antv/x6';
import { Sketch } from '@ckpack/vue-color';
import {
  Tabs as ATabs,
  TabPane as ATabPane,
  Form as AForm,
  FormItem as AFormItem,
  Input as AInput,
  InputNumber as AInputNumber,
  Popover as APopover,
  Row as ARow,
  Col as ACol,
  Button as AButton,
  Select as ASelect,
  Space as ASpace,
  Table as ATable,
} from 'ant-design-vue';

// Define props
const props = defineProps({
  node: {
    type: Node,
    required: true,
  },
});

// Define emits
const emit = defineEmits(['updateData']);

// Reactive state
const colors = ref({ r: 255, g: 0, b: 0 });
const presetColors = ref([
  '#f00',
  '#00ff00',
  '#00ff0055',
  'rgb(201, 76, 76)',
  'rgba(0,0,255,1)',
  'hsl(89, 43%, 51%)',
  'hsla(89, 43%, 51%, 0.6)',
]);
const fillColorVisible = ref(false);
const strokeColorVisible = ref(false);
const textColorVisible = ref(false);
const curBodyFill = ref('');
const curBodyStroke = ref('');
const curTextFill = ref('');
const curNode = ref(null);
const curLabel = ref('');
const curFontSize = ref('');
const form = reactive({});

// 属性
const formData = reactive({
  factoryName: '',
  factorySearch: '',
  lineName: '',
  lineSearch: '',
  productName: '',
  productSearch: '',
  isLatest: '',
  type: '',
  code: '',
  name: '',
  jph: '',
  version: '',
});
const yesNoOptions = [
  { label: '是', value: '是' },
  { label: '否', value: '否' },
];
const typeOptions = [
  { label: '生产', value: '生产' },
  { label: '生产1', value: '生产1' },
  { label: '生产2', value: '生产2' },
  { label: '生产3', value: '生产3' },
];

// 设备
const deviceColumns = [
  { title: '设备编码', dataIndex: 'code', key: 'code' },
  { title: '设备名称', dataIndex: 'name', key: 'name' },
  { title: '设备供应商', dataIndex: 'vendor', key: 'vendor' },
];
const deviceForm = reactive({
  code: '',
  name: '',
  vendor: '',
});
const deviceList = computed(() => props.node?.getData()?.deviceList || []);

// 模拟接口
const mockQueryById = async (productLineId) => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  return {
    factoryName: '示例工厂A',
    lineName: '产线B',
    productName: '产品C',
    isLatest: '是',
    type: '生产2',
    code: 'P-001',
    name: '工单名称测试',
    jph: '100',
    version: 'v1.2',
  };
};
const mockSaveFormData = async (data) => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  console.log('调用模拟保存接口，接收到数据：', data);
  return { success: true };
};
const mockAddDevice = async (payload) => {
  await new Promise((resolve) => setTimeout(resolve, 300));
  console.log('新增设备：', payload);
  return { success: true };
};

// Initialize curNode, curLabel, and curFontSize
watch(
    () => props.node,
    (newValue) => {
      curNode.value = newValue;
      curLabel.value = newValue.label || newValue.attrs?.label?.text || '';
      curFontSize.value = newValue.attrs?.text?.fontSize || '';
    },
    { immediate: true }
);

// Watch curNode changes
watch(curNode, (newValue) => {
  emit('updateData', newValue);
}, { deep: true });

// 属性相关
watchEffect(async () => {
  if (props.node?.id) {
    const data = await mockQueryById(props.node.id);
    Object.assign(formData, data);
    props.node.setData({ ...props.node.getData(), ...data });
  } else {
    const defaultData = await mockQueryById('canvas');
    Object.assign(formData, defaultData);
  }
});

// 保存属性
const handleSaveDeviceAttribute = async () => {
  const payload = {
    id: props.node?.id || '',
    factoryName: formData.factoryName,
    lineName: formData.lineName,
    productName: formData.productName,
    isLatest: formData.isLatest,
    type: formData.type,
    code: formData.code,
    name: formData.name,
    jph: formData.jph,
    version: formData.version,
  };
  const result = await mockSaveFormData(payload);
  if (result.success) {
    window.$message?.success?.('保存成功！');
    props.node.setData({ ...props.node.getData(), ...payload });
  } else {
    window.$message?.error?.('保存失败');
  }
};

// 设备相关
const handleDeviceSave = async () => {
  const payload = {
    productLineId: props.node?.id || '',
    nodeId: props.node?.id || '',
    ...deviceForm,
  };
  const result = await mockAddDevice(payload);
  if (result.success) {
    window.$message?.success?.('设备添加成功');
    const data = props.node.getData() || {};
    const existingList = data.deviceList || [];
    const newDevice = {
      code: deviceForm.code,
      name: deviceForm.name,
      vendor: deviceForm.vendor,
    };
    const updatedList = [...existingList, newDevice];
    props.node.setData({ ...data, deviceList: updatedList });
    deviceForm.code = '';
    deviceForm.name = '';
    deviceForm.vendor = '';
  }
};

// 修改标题
const handleLabel = (e) => {
  const value = e.target.value;
  if (curNode.value.attrs.label) {
    curNode.value.setAttrs({
      label: { text: value },
    });
  } else {
    curNode.value.setLabel(value);
  }
  curLabel.value = value;
};

// 修改字体大小
const handleFontsize = (value) => {
  curNode.value.setAttrs({
    text: { fontSize: Number(value) },
  });
  curFontSize.value = value;
};

// 更新填充色
const updateBodyFill = (v) => {
  curBodyFill.value = v.hex;
};

const handleBodyFill = () => {
  curNode.value.setAttrs({
    body: { fill: curBodyFill.value },
    top: { fill: curBodyFill.value },
  });
  fillColorVisible.value = false;
};

// 更新边框色
const updateBodyStroke = (v) => {
  curBodyStroke.value = v.hex;
};

const handleBodyStroke = () => {
  curNode.value.setAttrs({
    body: { stroke: curBodyStroke.value },
    top: { stroke: curBodyStroke.value },
  });
  strokeColorVisible.value = false;
};

// 更新文字颜色
const updateTextFill = (v) => {
  curTextFill.value = v.hex;
};

const handleTextFill = () => {
  curNode.value.setAttrs({
    text: { fill: curTextFill.value },
  });
  textColorVisible.value = false;
};
</script>

<style scoped>
.color-container {
  margin-top: 8px;
  width: 24px;
  height: 24px;
  padding: 4px;
  border: 1px solid #dfe3e8;
  border-radius: 2px;
}
.edit-color {
  cursor: pointer;
  height: 100%;
}
</style>
